package xyz.zhouzhaodong.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import xyz.zhouzhaodong.crm.dto.CustomerDto;
import xyz.zhouzhaodong.crm.dto.FormDto;
import xyz.zhouzhaodong.crm.dto.StaffDto;
import xyz.zhouzhaodong.crm.entity.Customer;
import xyz.zhouzhaodong.crm.entity.CustomerTypeTime;
import xyz.zhouzhaodong.crm.entity.Staff;
import xyz.zhouzhaodong.crm.mapper.CustomerMapper;
import xyz.zhouzhaodong.crm.mapper.CustomerTypeTimeMapper;
import xyz.zhouzhaodong.crm.mapper.StaffMapper;
import xyz.zhouzhaodong.crm.service.ICustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhouzhaodong.crm.util.RestMessage;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author zhouzhaodong
 * @since 2020-06-17
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Resource
    CustomerMapper customerMapper;

    @Resource
    CustomerTypeTimeMapper customerTypeTimeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage addCustomer(Customer customer) {
        try {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            customer.setId(id);
            customer.setCreateUser(customer.getStaffId());
            customer.setCreateTime(new Date());
            customerMapper.insert(customer);
            // 新增一个操作时间
            CustomerTypeTime customerTypeTime = new CustomerTypeTime();
            customerTypeTime.setCustomerId(customer.getId());
            customerTypeTime.setCustomerType(customer.getConnectType());
            customerTypeTime.setOperationTime(new Date());
            customerTypeTimeMapper.insert(customerTypeTime);
            return RestMessage.success(id);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage deleteCustomer(Customer customer) {
        try {
            customer.setId(customer.getId());
            customer.setFlag(1);
            customer.setConnectType("公海");
            customer.setUpdateUser(customer.getStaffId());
            customer.setUpdateTime(new Date());
            customerMapper.updateById(customer);
            // 新增一个操作时间
            CustomerTypeTime customerTypeTime = new CustomerTypeTime();
            customerTypeTime.setCustomerId(customer.getId());
            customerTypeTime.setCustomerType("公海");
            customerTypeTime.setOperationTime(new Date());
            customerTypeTimeMapper.insert(customerTypeTime);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage thoroughDelete(Customer customer) {
        try {
            customerMapper.deleteById(customer.getId());
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage updateCustomer(Customer customer) {
        try {
            customer.setUpdateUser(customer.getStaffId());
            customer.setUpdateTime(new Date());
            //不更新staffId
            customer.setStaffId(null);
            //这里需要添加以下时间记录，先查询之前状态是否发生了改变，如果改变就更新或者新增。
            String customerType = customer.getConnectType();
            String customerTypeOld = customerMapper.selectById(customer.getId()).getConnectType();
            if (customerType != null && !customerType.equals(customerTypeOld)) {
                // 查询和更新时间
                QueryWrapper<CustomerTypeTime> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("customer_id", customer.getId());
                queryWrapper.eq("customer_type", customerType);
                CustomerTypeTime customerTypeTime = customerTypeTimeMapper.selectOne(queryWrapper);
                if (customerTypeTime != null && customerTypeTime.getOperationTime() != null) {
                    // 更新
                    customerTypeTime.setOperationTime(new Date());
                    customerTypeTimeMapper.update(customerTypeTime, queryWrapper);
                } else {
                    customerTypeTime = new CustomerTypeTime();
                    customerTypeTime.setCustomerId(customer.getId().trim());
                    customerTypeTime.setCustomerType(customerType);
                    customerTypeTime.setOperationTime(new Date());
                    customerTypeTimeMapper.insert(customerTypeTime);
                }
            }
            //需要查询状态是否发生改变，如果改变就需要记录改变的时间
            customerMapper.updateById(customer);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage updateStaffId(Customer customer) {
        try {
            Customer c = new Customer();
            c.setId(customer.getId());
            c.setStaffId(customer.getStaffId());
            c.setConnectType("待沟通");
            c.setFlag(0);
            c.setUpdateUser(customer.getStaffId());
            c.setUpdateTime(new Date());
            customerMapper.updateById(c);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    public RestMessage selectById(String id) {
        Customer customer = customerMapper.selectById(id);
        return RestMessage.success(customer);
    }

    @Override
    public RestMessage selectByNumber(String number) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("number", number);
        queryWrapper.eq("flag", 0);
        List<Customer> list = customerMapper.selectList(queryWrapper);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectCustomer(CustomerDto customerDto) {
        if (customerDto.getPageNo() == 0 && customerDto.getPageSize() == 0) {
            List<Customer> list = customerMapper.selectList(null);
            return RestMessage.success(list);
        } else {
            Page<CustomerDto> page = new Page<>(customerDto.getPageNo(), customerDto.getPageSize());
            String connectType = customerDto.getConnectType();
//            String staffId = customerDto.getStaffId();
//            if (staffId != null && !"".equals(staffId)) {
//                StaffDto staffDto = staffMapper.selectStaffMessage(staffId);
//                if ("高校部".equals(staffDto.getDepartmentName())) {
//                    // staffId置空
//                    customerDto.setStaffId(null);
//                }
//            }
            if (connectType != null && !"".equals(connectType)) {
                String[] str = connectType.split(",");
                StringBuilder stringBuilder = new StringBuilder("(");
                for (String s : str) {
                    stringBuilder.append("'").append(s).append("',");
                }
                String newConnectType = stringBuilder.substring(0, stringBuilder.length() - 1) + ")";
                customerDto.setConnectType(newConnectType);
            }
            if (customerDto.getFlag() == null) {
                customerDto.setFlag(0);
            }
            IPage<CustomerDto> list = customerMapper.selectListPage(page, customerDto);
            return RestMessage.success(list);
        }

    }

    @Override
    public RestMessage selectLinkUp(CustomerDto customerDto) {
        Page<Customer> page = new Page<>(customerDto.getPageNo(),
                customerDto.getPageSize() == 0 ? 10 : customerDto.getPageSize());
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        if (customerDto.getStaffId() != null && !"".equals(customerDto.getStaffId())) {
            queryWrapper.eq("staff_id", customerDto.getStaffId());
        }
        if (customerDto.getName() != null && !"".equals(customerDto.getName())) {
            queryWrapper.like("name", customerDto.getName());
        }
        if (customerDto.getFlag() != null) {
            queryWrapper.eq("flag", customerDto.getFlag());
        } else {
            queryWrapper.eq("flag", 0);
        }
        queryWrapper.eq("connect_type", "待沟通");
        if (customerDto.getStudentSources() != null && !"".equals(customerDto.getStudentSources())) {
            queryWrapper.eq("student_sources", customerDto.getStudentSources());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<Customer> list = customerMapper.selectPage(page, queryWrapper);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectNum(CustomerDto customerDto) {
        // 查询主页显示数目
        Map<String, Integer> map = new HashMap<>(6);
        String staffId = customerDto.getStaffId();
        Integer flag = customerDto.getFlag() == null ? 0 : customerDto.getFlag();
        // 查询所有的客户
        Integer allCustomers = customerMapper.selectNum(staffId, flag, null);
        map.put("allCustomers", allCustomers);
        // 查询成交学生
        String connectType = "('成交')";
        Integer closeCustomer = customerMapper.selectCloseNum(staffId, flag, connectType);
        map.put("closeCustomer", closeCustomer);
        // 申请中
        connectType = "('补充材料','申请中','申请失败','预录取','完成录取')";
        Integer submitApplication = customerMapper.selectNum(staffId, flag, connectType);
        map.put("submitApplication", submitApplication);
        // 接机VIP
        connectType = "('接机VIP')";
        Integer pickUpVip = customerMapper.selectNum(staffId, flag, connectType);
        map.put("pickUpVip", pickUpVip);
        // 待审核（高校部）
        connectType = "('提交申请')";
        Integer pendingApproval = customerMapper.selectNum(null, flag, connectType);
        map.put("pendingApproval", pendingApproval);
        // 申请中（高校部）
        connectType = "('申请中')";
        Integer applying = customerMapper.selectNum(null, flag, connectType);
        map.put("applying", applying);
        // 待报到（高校部）
        connectType = "('待报道')";
        Integer pendingReported = customerMapper.selectNum(null, flag, connectType);
        map.put("pendingReported", pendingReported);
        return RestMessage.success(map);
    }

    @Override
    public RestMessage changeType(Customer customer) {
        // 修改客户状态
        if (customer.getStaffId() != null && !"".equals(customer.getStaffId())) {
            customer.setUpdateUser(customer.getStaffId());
            customer.setStaffId(null);
        }
        customer.setUpdateTime(new Date());
        customerMapper.updateById(customer);
        return RestMessage.success();
    }

    @Override
    public RestMessage selectCustomerDeal(CustomerDto customerDto) {
        // 固定列表显示，通过查询customer_type_time，客户状态操作时间表
        Page<CustomerDto> page = new Page<>(customerDto.getPageNo(),
                customerDto.getPageSize() == 0 ? 10 : customerDto.getPageSize());
        customerDto.setFlag(customerDto.getFlag() == null ? 0 : customerDto.getFlag());
        IPage<CustomerDto> list = customerMapper.selectCustomerDeal(page, customerDto);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectCustomerReport(CustomerDto customerDto) {
        // 待报到列表且为已邮寄
        Page<CustomerDto> page = new Page<>(customerDto.getPageNo(),
                customerDto.getPageSize() == 0 ? 10 : customerDto.getPageSize());
        customerDto.setFlag(customerDto.getFlag() == null ? 0 : customerDto.getFlag());
        IPage<CustomerDto> list = customerMapper.selectCustomerReport(page, customerDto);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectCustomerComplete(CustomerDto customerDto) {
        // 完成录取（需要关联申请表，且申请表status等于申请通过）
        Page<CustomerDto> page = new Page<>(customerDto.getPageNo(),
                customerDto.getPageSize() == 0 ? 10 : customerDto.getPageSize());
        customerDto.setFlag(customerDto.getFlag() == null ? 0 : customerDto.getFlag());
        IPage<CustomerDto> list = customerMapper.selectCustomerComplete(page, customerDto);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectCustomerToSchool(CustomerDto customerDto) {
        // 到校列表，固定
        Page<CustomerDto> page = new Page<>(customerDto.getPageNo(),
                customerDto.getPageSize() == 0 ? 10 : customerDto.getPageSize());
        customerDto.setFlag(customerDto.getFlag() == null ? 0 : customerDto.getFlag());
        IPage<CustomerDto> list = customerMapper.selectCustomerToSchool(page, customerDto);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectCustomerForm(FormDto formDto) {
        String entry = formDto.getEntry().trim();
        int flag = 0;
        // 顾问 申请状态 在校状态 成交列表
        String entryCheck = "顾问";
        if(entryCheck.equals(entry)){
            flag = 1;
            formDto.setEntry("staff_name");
        }
        entryCheck = "申请状态";
        if(entryCheck.equals(entry)){
            flag = 1;
            formDto.setEntry("type");
        }
        entryCheck = "在校状态";
        if(entryCheck.equals(entry)){
            flag = 1;
            formDto.setEntry("school_status");
        }
        entryCheck = "月别";
        if(entryCheck.equals(entry)){
            formDto.setEntry("month");
        }
        // 国家  性别  地区  专业  学校  学位   客户状态  入学季 经费来源
        entryCheck = "国家";
        if(entryCheck.equals(entry)){
            formDto.setEntry("country");
        }
        entryCheck = "性别";
        if(entryCheck.equals(entry)){
            formDto.setEntry("sex");
        }
        entryCheck = "地区";
        if(entryCheck.equals(entry)){
            formDto.setEntry("customer_area");
        }
        entryCheck = "专业";
        if(entryCheck.equals(entry)){
            formDto.setEntry("specialty");
        }
        entryCheck = "学校";
        if(entryCheck.equals(entry)){
            formDto.setEntry("school");
        }
        entryCheck = "学位";
        if(entryCheck.equals(entry)){
            formDto.setEntry("apply_degree");
        }
        entryCheck = "客户状态";
        if(entryCheck.equals(entry)){
            formDto.setEntry("connect_type");
        }
        entryCheck = "入学季";
        if(entryCheck.equals(entry)){
            formDto.setEntry("entrance_season");
        }
        entryCheck = "经费来源";
        if(entryCheck.equals(entry)){
            formDto.setEntry("source_funds");
        }
        if (flag == 1){
            return RestMessage.success(customerMapper.selectCustomerColleges(formDto));
        } else {
            return RestMessage.success(customerMapper.selectCustomerForm(formDto));
        }
    }
}
